package cn.alterzhang.www.test;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.ChildData;
import org.apache.curator.framework.recipes.cache.NodeCache;
import org.apache.curator.framework.recipes.cache.NodeCacheListener;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;

/**
 * Created by zhangshuhan on 2019/1/31.
 */
public class NodeCash {

    static CuratorFramework client = CuratorFrameworkFactory.newClient("198.181.39.68:2181", 5000, 3000, new ExponentialBackoffRetry(1000, 3));
    static String path = "/zk-book/nodeCash";

    public static void main(String[] args) throws Exception {
        client.start();
        client.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).forPath(path, "init".getBytes());
        NodeCache cache = new NodeCache(client, path, false);
        cache.start(true);
        cache.getListenable().addListener(new NodeCacheListener() {
            @Override
            public void nodeChanged() throws Exception {
                ChildData childData = cache.getCurrentData();
                if (null == childData) {
                    System.out.println("============已被删除无法获得数据===========");
                } else {
                    System.out.println("nodeDate update" + new String(childData.getData()));
                }

            }
        });
        client.setData().forPath(path, "java编程之美".getBytes());
        Thread.sleep(2000);
        client.delete().deletingChildrenIfNeeded().forPath(path);
        Thread.sleep(Integer.MAX_VALUE);
    }
}
